package com.yy.loramodule;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlarmManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.ToggleButton;

import com.yy.loramodule.bp.BpUartUtils;
import com.yy.sensor.Spo2HrData;
import com.yy.sensor.Spo2;

import java.lang.ref.WeakReference;
import java.util.Calendar;

public class MainActivity extends Activity implements OnClickListener,
        LoraSensor.SetParameterListener, LoraSensor.SendMessageListener,
        LoraSensor.MessageListener, LoraSensor.DeviceOperationListener,
        LoraSensor.SensorDataListener, LoraSensor.LoraDataListener {
    private static final String TAG = "MainActivity";

    Button bt_open_lora;
    private int flag = 0;
    Button bt_close_lora;
    Button bt_set_param;
    Button bt_send_data;
    TextView tv_recv_cont;

    ToggleButton tb_spoo_onoff;
    TextView tv_spoo_cont;
    TextView tv_hr_cont;

    TextView tv_hrv_cont;
    TextView tv_temp_cont;

    TextView tv_tx_num;
    TextView tv_rx_num;

    Spo2 spoo;

    public boolean firstBoot = false;

    MsgHandler msgHandler;

    @SuppressLint("UnspecifiedRegisterReceiverFlag")
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.d(TAG, "onCreate");
        setContentView(R.layout.activity_main);

//        grantPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE);
//        grantPermission(Manifest.permission.READ_EXTERNAL_STORAGE);

        bt_open_lora = findViewById(R.id.bt_open_lora);
        bt_close_lora = findViewById(R.id.bt_close_lora);
        bt_set_param = findViewById(R.id.bt_set_param);
        bt_send_data = findViewById(R.id.bt_send_data);
        tv_recv_cont = findViewById(R.id.tv_recv_cont);

        tv_hrv_cont = findViewById(R.id.tv_hrv_cont);
        tv_temp_cont = findViewById(R.id.tv_temp_cont);

        tv_tx_num = findViewById(R.id.tv_tx_num);
        tv_rx_num = findViewById(R.id.tv_rx_num);

        bt_open_lora.setOnClickListener(this);
        bt_close_lora.setOnClickListener(this);
        bt_set_param.setOnClickListener(this);
        bt_send_data.setOnClickListener(this);

        hideBottomUIMenu();

        spoo = new Spo2();

        msgHandler = new MsgHandler(this);

        ToggleButton tb_spoo_onoff = findViewById(R.id.tb_spoo_onoff);
        tb_spoo_onoff.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    spoo.open();
                    msgHandler.sendEmptyMessageDelayed(MSG_REFRESH_SPOO_DATA, 1000);
                } else {
                    spoo.close();
                    msgHandler.removeMessages(MSG_REFRESH_SPOO_DATA);
                }
            }
        });

        tv_spoo_cont = findViewById(R.id.tv_spoo_cont);
        tv_hr_cont = findViewById(R.id.tv_hr_cont);
        String ttl = "TTL:14";
        Logger.d("++++++++++" + Integer.parseInt( ttl.substring("TTL:".length()) ));

        //test
//        LoraSensor.getInstance().openLoRa(this);
//        boolean ret = BpUartUtils.getInstance().init(115200, "/dev/ttyS3");

//        IntentFilter filter = new IntentFilter();
//        filter.addAction("action.yy.bctest");
//        registerReceiver(receiver, filter);
        //Logger.d("+++canWrite+++++++" + Settings.System.canWrite(this));
//        if (Build.VERSION.SDK_INT > 23 && !Settings.System.canWrite(this)) {
//            // 如果没有修改系统的权限这请求修改系统的权限
//            Intent intent = new Intent(Settings.ACTION_MANAGE_WRITE_SETTINGS);
//            intent.setData(Uri.parse("package:" + getPackageName()));
//            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//            startActivity(intent);
//        }
        //boolean ret;
        //ret = Settings.Global.putInt(getApplicationContext().getContentResolver(), Settings.Global.AUTO_TIME, 0);
        //setSysTime(15, 20);

        //ret = Settings.System.putInt(getApplicationContext().getContentResolver(), Settings.System.SCREEN_BRIGHTNESS_MODE, 0);
        //Settings.System.putInt(getApplicationContext().getContentResolver(),
        //        Settings.System.SCREEN_BRIGHTNESS, 100);

        //ret = Settings.System.putString(getApplicationContext().getContentResolver(),
        //        "ethernet_static_ip", "5.5.5.5");
        //Logger.d("putString " + ret);
    }

    @SuppressLint("NonConstantResourceId")
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.bt_open_lora:
                LoraSensor.getInstance().openLoRa(this);
                LoraSensor.getInstance().setLoraDataListener(this);
                break;
            case R.id.bt_close_lora:
                flag = 0;
                LoraSensor.getInstance().closeLoRa(this);
                break;
            case R.id.bt_set_param:
                LoraSensor.WirelessParameter mWirelessParameter = new LoraSensor.WirelessParameter();
                mWirelessParameter.frequency = Integer.parseInt( ((EditText)findViewById(R.id.et_param_freq)).getText().toString() );
                mWirelessParameter.spreadingFactor = 8;
                mWirelessParameter.bandWidth = 125;
                mWirelessParameter.power = Integer.parseInt( ((EditText)findViewById(R.id.et_param_power)).getText().toString() );
                mWirelessParameter.address = Integer.parseInt( ((EditText)findViewById(R.id.et_param_id)).getText().toString() );
                mWirelessParameter.groupAddress = new int[]{Integer.parseInt( ((EditText)findViewById(R.id.et_param_group)).getText().toString() ),};
                mWirelessParameter.forward = true;
                mWirelessParameter.sleepPercent = 50;
                LoraSensor.getInstance().setWirelessParameter(mWirelessParameter, this);
                break;
            case R.id.bt_send_data:
                flag = 1;
                LoraSensor.SendMessage mSendMessage = new LoraSensor.SendMessage();
                mSendMessage.ack = ((ToggleButton)findViewById(R.id.tb_ack)).isChecked() ? 1 : 0;
                mSendMessage.seqNo = 11;
                mSendMessage.msgType = ((ToggleButton)findViewById(R.id.tb_msg_type)).isChecked() ? 1 : 0;
                mSendMessage.nodeAddress = Integer.parseInt( ((EditText)findViewById(R.id.et_node_add)).getText().toString() );
                mSendMessage.targatAddress = Integer.parseInt( ((EditText)findViewById(R.id.et_targat_add)).getText().toString() );
                mSendMessage.forwardNum = Integer.parseInt( ((EditText)findViewById(R.id.et_forward_num)).getText().toString() );
                mSendMessage.content = new byte[]{
                                                '1', '2', '3','a','b','c','d','e','f','g',
                                                'b', 'b', 'b','b','b','b','b','b','b','b',
                                                 'c', 'c', 'c','c','c','c','c','c','c','c',
                                                 'd','f'
                                                };
                LoraSensor.getInstance().sendMsg(mSendMessage, MainActivity.this);
/*
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        Log.i("stephen MainActivity----", "使用匿名类方式实现线程");
                        while (flag > 0) {
                            try {
                                Thread.sleep(1000 * 30);//
                                Log.i("stephen ", "send lora");
                                LoraSensor.getInstance().sendMsg(mSendMessage, MainActivity.this);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                }).start();

 */
                break;

        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        Logger.d("stephen onKeyDown keyCode:" + keyCode);
        if (keyCode == KeyEvent.KEYCODE_F4) {
            Log.d("stephen KeyEvent", "KEYCODE_EXPLORER Down pressed");
            return true; // 返回true表示事件已处理，不继续传递。
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        Logger.d("stephen  onKeyUp keyCode:" + keyCode);
        if (keyCode == KeyEvent.KEYCODE_F4) {
            Log.d("stephen KeyEvent", "KEYCODE_EXPLORER Down released send lora");
            LoraSensor.SendMessage mSendMessage = new LoraSensor.SendMessage();
            mSendMessage.ack = ((ToggleButton)findViewById(R.id.tb_ack)).isChecked() ? 1 : 0;
            mSendMessage.seqNo = 11;
            mSendMessage.msgType = ((ToggleButton)findViewById(R.id.tb_msg_type)).isChecked() ? 1 : 0;
            mSendMessage.nodeAddress = Integer.parseInt( ((EditText)findViewById(R.id.et_node_add)).getText().toString() );
            mSendMessage.targatAddress = Integer.parseInt( ((EditText)findViewById(R.id.et_targat_add)).getText().toString() );
            mSendMessage.forwardNum = Integer.parseInt( ((EditText)findViewById(R.id.et_forward_num)).getText().toString() );
            mSendMessage.content = new byte[]{
                    '1', '2', '3','a','b','c','d','e','f','g',
                    'b', 'b', 'b','b','b','b','b','b','b','b',
                    'c', 'c', 'c','c','c','c','c','c','c','c',
                    'd','f',
                    'q', 'a', 'z','a','b','c','d','e','f','g',
                    'b', 'b', 'b','b','b','b','b','b','b','b',
                    'c', 'c', 'c','c','c','c','c','c','c','c',
                    'd','f'
            };
			LoraSensor.getInstance().sendMsg(mSendMessage, MainActivity.this);
            return true; // 返回true表示事件已处理，不继续传递。
        }
        return super.onKeyUp(keyCode, event);
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.d(TAG, "onResume" + Double.BYTES + " " + Byte.SIZE);
        if ( firstBoot ) {
            return ;
        }
        firstBoot = true;

        LoraSensor.getInstance().registerMsg(this);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.e(TAG, "onDestroy");
//        unregisterReceiver();
        LoraSensor.getInstance().closeLoRa(this);
    }

    @Override
    public void loraDataRTNum(int sendNum, int recvNum) {
        runOnUiThread(new Runnable() {
            @SuppressLint("SetTextI18n")
            @Override
            public void run() {
                tv_tx_num.setText(getString(R.string.str_send_num) + sendNum);
                tv_rx_num.setText(getString(R.string.str_recv_num) + recvNum);
            }
        });
    }

    @Override
    public void isSetParameterSuccessful(boolean state) {

    }

    @Override
    public void isSendMessageSuccesful(boolean state) {

    }

    @Override
    public void receiveMsg(LoraSensor.RecvMessage msg) {
    }

    @Override
    public void receiveStr(String msg) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                tv_recv_cont.setText(msg);
            }
        });
    }

    @Override
    public void isDeviceOperationSuccessful(boolean state) {

    }

    @Override
    public void sensorDataCallback(byte[] data) {

    }

    public void setSysTime(int hour, int minute){
        Calendar c = Calendar.getInstance();
        c.set(Calendar.HOUR_OF_DAY, hour);
        c.set(Calendar.MINUTE, minute);
        c.set(Calendar.SECOND, 0);
        c.set(Calendar.MILLISECOND, 0);

        long when = c.getTimeInMillis();

        if(when / 1000 < Integer.MAX_VALUE){
            ((AlarmManager)this.getSystemService(Context.ALARM_SERVICE)).setTime(when);
        }
    }

    private LoraReceiver receiver = new LoraReceiver();

    public static class LoraReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            Log.d("LoraReceiver", "==BroadcastReceiver "
                    + intent + " action " + intent.getAction());
        }
    }

    public void unregisterReceiver() {
        if (receiver != null) {
            unregisterReceiver(receiver);
            receiver = null;
        }
    }

    public static final int MSG_REFRESH_SPOO_DATA = 1000001;
    private class MsgHandler extends Handler {

        private WeakReference<MainActivity> ref;

        MsgHandler(MainActivity button) {
            ref = new WeakReference<MainActivity>(button);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            MainActivity act = ref.get();
            switch (msg.what) {
                case MSG_REFRESH_SPOO_DATA:
                    Spo2HrData spo2Hr = spoo.getSpo2Hr();
                    Log.d(TAG, "getSpo2Hr " + spo2Hr.toString());

                    tv_spoo_cont.setText(spo2Hr.getSpo2Value() + "");
                    tv_hr_cont.setText(spo2Hr.getHrValue() + "");
                    tv_hrv_cont.setText(spo2Hr.getHrv() + "");
                    tv_temp_cont.setText(spo2Hr.getTemperature() + "");

                    msgHandler.sendEmptyMessageDelayed(MSG_REFRESH_SPOO_DATA, 1000);
                    break;
            }
        }
    }

    protected void hideBottomUIMenu() {
        int flags;
        int curApiVersion = android.os.Build.VERSION.SDK_INT;
        // This work only for android 4.4+
        if(curApiVersion >= Build.VERSION_CODES.KITKAT){

            // This work only for android 4.4+
            // hide navigation bar permanently in android activity
            // touch the screen, the navigation bar will not show

            flags = View.SYSTEM_UI_FLAG_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_IMMERSIVE
                    | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION;
        }else{
            // touch the screen, the navigation bar will show
            flags = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION|
                    View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION;
        }

        // must be executed in main thread :)
        getWindow().getDecorView().setSystemUiVisibility(flags);
    }

}
